import { Component, OnInit } from '@angular/core';
import { UserService } from './user.service';
import { User } from './user';

import { ChangeDetectorRef } from '@angular/core';
import { Global } from 'src/global';
import { PokemonService } from '../pokemon/pokemon.service';

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css'],
})
export class UserComponent implements OnInit {
  constructor(
    private userService: UserService,
    private changeDetectorRef: ChangeDetectorRef,
    private pokemonService: PokemonService
  ) {}

  users: User[] = new Array();
  type: string = '';
  old_user: string ='';
  new_user: User = new User();
  login_user = Global.user;

  ngOnInit(): void {
    this.pokemonService.get_user(this.login_user.username).subscribe((res) => {
      if (res['status'] == 'ok') {
        this.login_user = res['data'];
        // console.log(this.pokemon)
      }
    });
    this.getUsers(); //调用
  }
  getUsers() {
    //调用service中的同名方法
    this.userService.getUsers().subscribe((data) => {
      this.users = data['datas'];
      // console.log(this.users)
    });
  }
  deleteUser(user: User) {
    // console.log(1111)
    this.userService.deleteUser(user).subscribe((res) => {
      this.getUsers();
    });

    this.changeDetectorRef.markForCheck();
    this.changeDetectorRef.detectChanges();
  }
  editUser(user: User, type: string,old_user:string) {
    if (type == 'ADD') {
      this.userService.addUser(user).subscribe((data) => {
        document.getElementById('closeModalButton')?.click();
        this.getUsers();
        // this.changeDetectorRef.markForCheck();
        // this.changeDetectorRef.detectChanges();
      });
    } else {
      this.userService.editUser(user,old_user).subscribe((data) => {
        document.getElementById('closeModalButton')?.click();
        // this.changeDetectorRef.markForCheck();
        // this.changeDetectorRef.detectChanges();
        this.getUsers();
      });
    }
    this.changeDetectorRef.markForCheck();
    this.changeDetectorRef.detectChanges();
  }
}
